import React from 'react';
import {Modal, Icon} from 'antd';
import {TimePicker, Input, Row, Col, Form, Button,Select} from 'antd';
import axios from 'axios';
import {sessionManager} from '../../utils/sessionStorage';
import {UUID} from '../../utils/tranStartType'
import moment from 'moment';
import { injectIntl } from 'react-intl';

const FormItem = Form.Item;
const createForm = Form.create;
const Option = Select.Option;
let uuid = 0;

class modifyPrice extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            confirmLoading: false,
            mode: 'time'
        }
    }

    //父组件改变时，子组件监听props
    componentWillReceiveProps(nextProps) {
        //公司内部电价有可能没设置 length会报错
        if (nextProps.privatePrices && (nextProps.privatePrices.length != this.props.privatePrices.length)) {
            uuid = nextProps.privatePrices.length;
        }
        this.setState({
            visible: nextProps.visible,
        });
    }

    handleOk = () => {
        this.setState({
            visible: false,
            confirmLoading: false,
        });
    }
    /*--------表格---------*/
    remove = (k) => {
        const {form} = this.props;
        // can use data-binding to get
        const keys = form.getFieldValue('keys');
        // We need at least one passenger
        console.log('removeKeys: ', keys, 'k:', k);
        uuid--;
        // if (keys.length === 1) {
        //     return;
        // }
        // can use data-binding to set
        form.setFieldsValue({
            keys: keys.filter(key => key !== k),
        });
    }
    add = () => {
        const {form} = this.props;
        // can use data-binding to get
        const keys = form.getFieldValue('keys');
        uuid++;
        const nextKeys = keys.concat({uuidKeys: UUID()});
        //超过15个直接返回
        if (uuid >= 16) {
            return
        }
        console.log('uuid: ', uuid);
        // can use data-binding to set
        // important! notify form to detect changes

        form.setFieldsValue({
            keys: nextKeys,
        });
    }
    maxNumber = (rule, value, callback) => {
        if (value > 100) {
            callback('最大金额为100');
        } else {
            callback();
        }
    }
    endTimeLess = (rule, value, callback) => {
        const form = this.props.form;
        let index = rule.field.substring(8, 9);
        if (value < form.getFieldValue(`startTime[${index}]`)) {
            callback('不能小于开始时间');
        } else {
            callback();
        }
    }
    transformTime = (data) => {
        if (data <= 9) {
            data = '0' + data
        }
        return data
    };
    /*--------表格---------*/
    onChange = (date, dateString) => {
        console.log(dateString)
    }
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((errors, values) => {
            if (!!errors || values.keys.length == 0) {
                console.log('Errors in form!!!');
                return;
            }
            console.log('Submit!!!', values);
            let params = [];
            values.keys.map((item, index) => {
                let startTime = values.startTime[index].format('HHmm');
                let startArr = [startTime, values.electricityPrice[index], values.servicePrice[index]];
                if(values.range[index]){
                    startArr[3]=values.range[index];
                }
                params.push(startArr);
            });
            let stuGroupID = sessionManager.get('selectStuGroup').id;
            //
            axios.post('/api/stubGroup/price/mod', {
                stubGroupId: stuGroupID,
                feeInfoStr: JSON.stringify(params),
            }).then(res => {
                console.log('修改电价', res);
                if (res && res.code == 200) {
                    this.props.getStubGroupPrice();
                    this.props.handleCancel();
                    this.props.form.resetFields();
                }
            })
        });
    };

    render() {
        /*------------------表格验证--------------*/
        const formItemLayout = {
            labelCol: {
                xl: {span: 8},
                xxl: {span: 8}
            },
            wrapperCol: {
                xl: {span: 16},
                xxl: {span: 16}
            }
        };
        const {getFieldDecorator, getFieldValue} = this.props.form;
        console.log('this.props.privatePrices',this.props.privatePrices);
        getFieldDecorator('keys', {initialValue: this.props.privatePrices || []});
        const format = 'HH:mm';
        const keys = getFieldValue('keys');
        const common = this.props.intl.messages.common;
        const formItems = keys.map((k, index) => {
            return (
                <FormItem
                    required={false}
                    key={k.uuidKeys}
                >
                    <Row gutter={16}>
                    <Col span={4}>
                            <FormItem
                            >
                                {getFieldDecorator(`range[${index}]`,{
                                    initialValue:k.range
                                })(
                                <Select placeholder={'计费区间'} allowClear={true} optionLabelProp="children">
                                    <Option value={1}>峰时</Option>
                                    <Option value={2}>尖时</Option>
                                    <Option value={3}>谷时</Option>
                                    <Option value={4}>平时</Option>
                                </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={6}>
                            {!k.startTime ?
                                <FormItem>
                                    {getFieldDecorator(`startTime[${index}]`,
                                        {
                                            rules: [{type: 'object', required: true, message: common.PleaseSelectStartTime}],
                                        }
                                    )(
                                        <TimePicker placeholder={common.startTime} format={format}/>
                                    )}
                                </FormItem>
                                :
                                <FormItem>
                                    {getFieldDecorator(`startTime[${index}]`,
                                        {
                                            rules: [{type: 'object', required: true, message: common.PleaseSelectStartTime}],
                                            initialValue: moment(k.startTime, 'HH:mm')
                                        }
                                    )(
                                        <TimePicker disabled={index === 0} format={format}/>
                                    )}
                                </FormItem>
                            }

                        </Col>
                        <Col span={6}>
                            <FormItem
                                {...formItemLayout}
                                label={common.energyChargeUnit}
                            >
                                {getFieldDecorator(`electricityPrice[${index}]`, {
                                    rules: [
                                        {required: true, message: common.PleaseInputElectricityBill,},
                                        {validator: this.maxNumber,}
                                    ],
                                    initialValue: k.electricityPrice

                                })(
                                    <Input/>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={6}>
                            <FormItem
                                {...formItemLayout}
                                label={common.serviceChargeUnit}
                            >
                                {getFieldDecorator(`servicePrice[${index}]`, {
                                    rules: [
                                        {required: true, message: common.PleaseEnterServiceCharge,},
                                        {validator: this.maxNumber,}
                                    ],
                                    initialValue: k.servicePrice
                                })(
                                    <Input/>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={2}>
                            {index !== 0 && keys.length > 1 ? (
                                <Icon
                                    className="dynamic-delete-button"
                                    type="minus-circle-o"
                                    disabled={keys.length === 1}
                                    onClick={() => this.remove(k)}
                                />
                            ) : null}
                        </Col>
                    </Row>
                </FormItem>
            );
        });
        /*------------------表格验证--------------*/
        const {visible, confirmLoading} = this.state;
        return (
            <div>
                {visible&&<Modal title={common.adjustPriceOfEnterprise}
                       visible={visible}
                       onOk={this.handleSubmit}
                       confirmLoading={confirmLoading}
                       onCancel={this.props.handleCancel}
                       width={800}
                >
                    <Form onSubmit={this.handleSubmit}>
                        {formItems}
                        <Button type="dashed" onClick={this.add} style={{width: '60%'}}>
                            <Icon type="plus"/> {common.AddTimePeriod}
                        </Button>
                    </Form>
                </Modal>}
            </div>
        );
    }
}

modifyPrice = createForm()(modifyPrice);
export default injectIntl(modifyPrice);